<template>
  <div class="batch-container">
    <div class="batch-wrapper">
      <div class="batch-body">
        <div class="batch-content-wrapper">
          <!-- 左侧：文件上传和参数设置 -->
          <div class="batch-input-section">
            <div class="card">
              <div class="card-title">
                <i class="el-icon-document"></i>
                <span>文件处理</span>
                <div class="card-actions">
                  <el-button type="danger" size="small" @click="clearAllFiles" :disabled="fileList.length === 0">
                    清空文件
                  </el-button>
                </div>
              </div>
              <div class="batch-content">
                <div class="batch-upload-section">
                  <div class="upload-area">
                    <el-upload class="upload-box" action="#" :auto-upload="false" :on-change="handleFileChange"
                      :on-remove="handleRemove" multiple accept=".csv" drag :file-list="fileList" ref="uploadRef">
                      <i class="el-icon-upload"></i>
                      <div class="el-upload__text">拖拽多个文件到此处或 <em>点击上传</em></div>
                      <template #tip>
                        <div class="el-upload__tip">可以选择多个CSV文件进行批量处理</div>
                      </template>
                    </el-upload>
                  </div>
                </div>

                <div class="batch-params-section">
                  <div class="section-title">计算参数</div>
                  <div class="setting-control params-row">
                    <div class="param-item">
                      <div class="param-label">倍数系数</div>
                      <el-input-number v-model="multiplier" :min="0.1" :max="1.0" :step="0.1" :precision="1"
                        placeholder="倍数系数" style="width: 100%"></el-input-number>
                    </div>
                    <div class="param-item">
                      <div class="param-label">汇率</div>
                      <el-input-number v-model="exchangeRate" :min="0.01" :max="100" :step="0.01" :precision="2"
                        placeholder="请输入汇率" style="width: 100%"></el-input-number>
                    </div>
                  </div>

                  <div class="batch-actions">
                    <el-button type="primary" @click="processBatch" :disabled="fileList.length === 0">
                      开始批量处理
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧：处理结果 -->
          <div class="batch-result-section">
            <div class="card results-card">
              <div class="card-title">
                <i class="el-icon-data-analysis"></i>
                <span>处理结果</span>
              </div>
              <div class="batch-filter">
                <div class="filter-item">
                  <div class="filter-label">用户名</div>
                  <el-input v-model="fileNameFilter" placeholder="请输入用户名关键词" clearable @input="applyFilters">
                    <template #prefix>
                      <i class="el-icon-search"></i>
                    </template>
                  </el-input>
                </div>
                <div class="filter-item date-filter-item">
                  <div class="filter-label">开始日期</div>
                  <el-date-picker v-model="startDateFilter" type="date" placeholder="选择开始日期" :clearable="true"
                    @change="applyFilters" :shortcuts="[]"></el-date-picker>
                </div>
                <div class="filter-item date-filter-item">
                  <div class="filter-label">结束日期</div>
                  <el-date-picker v-model="endDateFilter" type="date" placeholder="选择结束日期" :clearable="true"
                    @change="applyFilters" :shortcuts="[]"></el-date-picker>
                </div>
                <div class="filter-actions">
                  <el-button type="primary" @click="exportToExcel" :disabled="filteredResults.length === 0"
                    size="small">
                    <el-icon class="el-icon--left">
                      <Download />
                    </el-icon>批量导出Excel
                  </el-button>
                  <el-button type="info" @click="resetFilters" size="small">
                    重置
                  </el-button>
                </div>
              </div>

              <div class="batch-results">
                <el-table :data="filteredResults" style="width: 100%" border
                  :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold', textAlign: 'center' }"
                  :row-style="{ height: '40px' }">
                  <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
                  <el-table-column prop="userName" label="用户名" min-width="90" align="center"></el-table-column>
                  <el-table-column prop="startDate" label="开始时间" min-width="130" align="center">
                    <template #default="scope">
                      <div v-if="startDateFilter && !isStartDateMatch(scope.row)"
                        style="color: red; display: inline-block;">
                        {{ scope.row && scope.row.startDate ? formatDateTime(scope.row.startDate) : '无数据' }}
                      </div>
                      <div v-else style="display: inline-block;">
                        {{ scope.row && scope.row.startDate ? formatDateTime(scope.row.startDate) : '无数据' }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="endDate" label="结束时间" min-width="130" align="center">
                    <template #default="scope">
                      <div v-if="endDateFilter && !isEndDateMatch(scope.row)"
                        style="color: red; display: inline-block;">
                        {{ scope.row && scope.row.endDate ? formatDateTime(scope.row.endDate) : '无数据' }}
                      </div>
                      <div v-else style="display: inline-block;">
                        {{ scope.row && scope.row.endDate ? formatDateTime(scope.row.endDate) : '无数据' }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="recordCount" label="记录数" min-width="80" align="center"></el-table-column>
                  <el-table-column prop="totalProfit" label="总利润" min-width="100" align="center">
                    <template #default="scope">
                      <span class="highlight-profit">
                        {{ scope.row.totalProfit ? scope.row.totalProfit.toFixed(2) : '0.00' }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="totalCommission" label="手续费" min-width="100" align="center">
                    <template #default="scope">
                      {{ scope.row.totalCommission ? scope.row.totalCommission.toFixed(2) : '0.00' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="totalSwap" label="库存费" min-width="100" align="center">
                    <template #default="scope">
                      {{ scope.row.totalSwap ? scope.row.totalSwap.toFixed(2) : '0.00' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="originalTotal" label="原始金额" min-width="100" align="center">
                    <template #default="scope">
                      <span class="highlight-result-without-calculate">
                        {{ scope.row.originalTotal ? scope.row.originalTotal.toFixed(2) : '0.00' }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="finalResult" label="结果" min-width="100" align="center">
                    <template #default="scope">
                      <span class="highlight-result">
                        {{ scope.row.finalResult ? scope.row.finalResult.toFixed(2) : '0.00' }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120" fixed="right" align="center">
                    <template #default="scope">
                      <div class="action-buttons">
                        <el-tooltip content="复制结果" placement="top" effect="light">
                          <el-button type="text" @click="copyResult(scope.row)" class="copy-btn">
                            <el-icon>
                              <Document />
                            </el-icon>
                          </el-button>
                        </el-tooltip>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import Papa from 'papaparse'
import { Document, Download } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'

// 状态变量
const fileList = ref([])
const multiplier = ref(0.3)
const exchangeRate = ref(7.1) // 默认汇率为7.1（美元兑人民币）
const batchResults = ref([])
const fileNameFilter = ref('')
const startDateFilter = ref(null)
const endDateFilter = ref(null)
const uploadRef = ref(null)

// 不再使用日期快捷选项

// 过滤后的结果 - 只根据用户名筛选
const filteredResults = computed(() => {
  let results = batchResults.value

  // 应用用户名过滤
  if (fileNameFilter.value) {
    results = results.filter(item => {
      return item.userName.toLowerCase().includes(fileNameFilter.value.toLowerCase())
    })
  }

  return results
})

// 检查开始日期是否匹配
const isStartDateMatch = (item) => {
  // 检查参数是否有效
  if (!item) return true

  // 如果没有设置筛选日期或文件没有开始日期，则视为匹配
  if (!startDateFilter || !startDateFilter.value || !item.startDate) return true

  try {
    // 获取日期的年月日字符串 (YYYY-MM-DD)
    const getDateString = (date) => {
      if (!date) return null

      let dateObj
      if (date instanceof Date) {
        dateObj = date
      } else {
        dateObj = new Date(date)
        if (isNaN(dateObj.getTime())) {
          console.error('无效的日期对象:', date)
          return null
        }
      }

      const year = dateObj.getFullYear()
      const month = String(dateObj.getMonth() + 1).padStart(2, '0')
      const day = String(dateObj.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }

    // 获取文件开始日期的年月日字符串
    const itemStartDateStr = getDateString(item.startDate)

    // 获取筛选条件开始日期的年月日字符串
    const filterStartDateStr = getDateString(startDateFilter.value)

    // 如果无法获取有效的日期字符串，则视为不匹配
    if (!itemStartDateStr || !filterStartDateStr) return false

    // 比较两个日期字符串是否相等
    const isMatch = itemStartDateStr === filterStartDateStr




    return isMatch
  } catch (error) {
    return true
  }
}

// 检查结束日期是否匹配
const isEndDateMatch = (item) => {
  // 检查参数是否有效
  if (!item) return true

  // 如果没有设置筛选日期或文件没有结束日期，则视为匹配
  if (!endDateFilter || !endDateFilter.value || !item.endDate) return true

  try {
    // 获取日期的年月日字符串 (YYYY-MM-DD)
    const getDateString = (date) => {
      if (!date) return null

      let dateObj
      if (date instanceof Date) {
        dateObj = date
      } else {
        dateObj = new Date(date)
        if (isNaN(dateObj.getTime())) {
          console.error('无效的日期对象:', date)
          return null
        }
      }

      const year = dateObj.getFullYear()
      const month = String(dateObj.getMonth() + 1).padStart(2, '0')
      const day = String(dateObj.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }

    // 获取文件结束日期的年月日字符串
    const itemEndDateStr = getDateString(item.endDate)

    // 获取筛选条件结束日期的年月日字符串
    const filterEndDateStr = getDateString(endDateFilter.value)

    // 如果无法获取有效的日期字符串，则视为不匹配
    if (!itemEndDateStr || !filterEndDateStr) return false

    // 比较两个日期字符串是否相等
    const isMatch = itemEndDateStr === filterEndDateStr



    return isMatch
  } catch (error) {
    return true
  }
}

// 检查文件的开始日期和结束日期是否与选择的日期精确匹配（只比较年月日）
const isDateInRange = (item) => {
  // 如果没有设置任何日期筛选条件，则所有行都匹配
  if (!startDateFilter.value && !endDateFilter.value) {
    return true
  }

  // 如果文件没有日期数据，则视为不匹配
  if (!item.startDate || !item.endDate) {
    return false
  }

  try {
    // 提取日期的年月日部分，返回YYYY-MM-DD格式的字符串
    const getDateString = (date) => {
      if (!date) return null

      let dateObj
      if (date instanceof Date) {
        dateObj = date
      } else {
        // 如果是字符串，先检查是否已经是YYYY-MM-DD格式
        if (typeof date === 'string' && date.match(/^\d{4}-\d{2}-\d{2}$/)) {
          return date // 已经是YYYY-MM-DD格式，直接返回
        }

        dateObj = new Date(date)
        if (isNaN(dateObj.getTime())) {
          return null
        }
      }

      const year = dateObj.getFullYear()
      const month = String(dateObj.getMonth() + 1).padStart(2, '0')
      const day = String(dateObj.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }

    // 获取文件的开始和结束日期（仅年月日，格式为YYYY-MM-DD）
    const itemStartDateStr = getDateString(item.startDate)
    const itemEndDateStr = getDateString(item.endDate)

    // 获取筛选条件的日期（仅年月日，格式为YYYY-MM-DD）
    const filterStartDateStr = getDateString(startDateFilter.value)
    const filterEndDateStr = getDateString(endDateFilter.value)

    if (!itemStartDateStr || !itemEndDateStr) {
      return false // 如果无法获取有效的文件日期，则视为不匹配
    }

    // 检查是否完全匹配选择的日期范围
    let isInRange = true

    // 检查开始日期和结束日期是否分别匹配（任一不匹配则标红）
    let startMatches = true
    let endMatches = true

    // 如果设置了开始日期，检查文件的开始日期是否匹配
    if (filterStartDateStr) {
      startMatches = filterStartDateStr === itemStartDateStr
    }

    // 如果设置了结束日期，检查文件的结束日期是否匹配
    if (filterEndDateStr) {
      endMatches = filterEndDateStr === itemEndDateStr
    }

    // 只要有一个不匹配，就标记为不在范围内（需要标红）
    // 注意：这里返回true表示匹配，false表示不匹配（需要标红）
    isInRange = startMatches && endMatches



    // 返回true表示匹配，false表示不匹配（需要标红）
    return isInRange
  } catch (error) {
    return true // 出错时默认不标红
  }
}

// 重置过滤器
const resetFilters = () => {
  fileNameFilter.value = '';
  startDateFilter.value = null;
  endDateFilter.value = null;

  ElMessage({
    message: '已重置所有筛选条件',
    type: 'success',
    duration: 1500
  });
}

// 应用过滤器
const applyFilters = () => {
  // 过滤逻辑由计算属性处理
  console.log('应用日期筛选 - 原始值:', {
    开始日期: startDateFilter.value,
    结束日期: endDateFilter.value,
    开始日期类型: startDateFilter.value ? typeof startDateFilter.value : 'null',
    结束日期类型: endDateFilter.value ? typeof endDateFilter.value : 'null'
  })

  // 记录日期对象信息，便于调试
  if (startDateFilter.value) {
    try {
      const date = startDateFilter.value instanceof Date
        ? startDateFilter.value
        : new Date(startDateFilter.value)

      console.log('开始日期详情:', {
        原始值: startDateFilter.value,
        对象类型: typeof startDateFilter.value,
        是否日期对象: startDateFilter.value instanceof Date,
        转换后日期: date.toLocaleDateString(),
        年: date.getFullYear(),
        月: date.getMonth() + 1,
        日: date.getDate()
      })
    } catch (error) {
      console.error('开始日期解析错误:', error, startDateFilter.value)
    }
  }

  if (endDateFilter.value) {
    try {
      const date = endDateFilter.value instanceof Date
        ? endDateFilter.value
        : new Date(endDateFilter.value)

      console.log('结束日期详情:', {
        原始值: endDateFilter.value,
        对象类型: typeof endDateFilter.value,
        是否日期对象: endDateFilter.value instanceof Date,
        转换后日期: date.toLocaleDateString(),
        年: date.getFullYear(),
        月: date.getMonth() + 1,
        日: date.getDate()
      })
    } catch (error) {
      // 错误处理
    }
  }

  // 强制重新渲染表格
  if (startDateFilter.value || endDateFilter.value) {
    // 创建一个临时变量并赋值回去，触发视图更新
    const temp = [...batchResults.value]
    batchResults.value = []
    setTimeout(() => {
      batchResults.value = temp
    }, 0)
  }
}

// 设置表格行的类名
const tableRowClassName = ({ row, rowIndex }) => {
  // 如果设置了日期筛选条件
  if (startDateFilter.value || endDateFilter.value) {
    // 检查文件的日期是否与选择的日期匹配
    // 不匹配则标记为红色
    const isMatching = isDateInRange(row)

    if (!isMatching) {

      // 直接返回字符串而不是对象，确保类名被正确应用
      return 'out-of-range-row'
    }
  }
  return ''
}

// 处理文件上传
const handleFileChange = (file) => {
  if (file && file.raw) {
    // 检查是否已经存在同名文件
    const existingFile = fileList.value.find(f => f.name === file.name)
    if (existingFile) {
      ElMessage({
        message: `文件 ${file.name} 已存在`,
        type: 'warning',
        duration: 2000
      })
      return
    }

    // 将文件添加到文件列表
    fileList.value.push(file)
  }
}

// 处理文件移除
const handleRemove = (file) => {
  const index = fileList.value.findIndex(f => f.name === file.name)
  if (index !== -1) {
    fileList.value.splice(index, 1)
    ElMessage({
      message: `已移除文件：${file.name}`,
      type: 'success',
      duration: 1500
    })
  }
}

// 清空所有文件
const clearAllFiles = () => {
  if (fileList.value.length === 0) {
    return
  }

  fileList.value = []

  // 清空上传组件的文件列表
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }

  // 清空右侧表格数据
  batchResults.value = []

  // 重置筛选条件
  fileNameFilter.value = ''
  startDateFilter.value = null
  endDateFilter.value = null

  ElMessage({
    message: '已清空所有文件和处理结果',
    type: 'success',
    duration: 1500
  })
}

// 切换文件选择状态
const toggleFileSelection = (file) => {
  // 此功能可以根据需要实现，例如将文件标记为已选择或未选择
  console.log('切换文件选择状态:', file.name)
  // 这里暂时不做实际操作，保持所有文件都是选中状态
}

// 批量处理文件
const processBatch = async () => {
  if (fileList.value.length === 0) {
    ElMessage({
      message: '请先上传CSV文件',
      type: 'warning',
      duration: 2000
    })
    return
  }

  batchResults.value = []
  console.log('开始处理文件，文件数量:', fileList.value.length)

  try {
    // 逐个处理文件
    for (const file of fileList.value) {
      console.log('处理文件:', file.name)
      const result = await processFile(file)
      console.log('文件处理结果:', result)

      if (result) {
        // 从文件名中提取用户名 (格式: 用户名+文件名.csv)
        let userName = file.name
        const plusIndex = file.name.indexOf('+')
        if (plusIndex !== -1) {
          userName = file.name.substring(0, plusIndex)
        }

        batchResults.value.push({
          fileName: file.name,
          userName: userName,
          recordCount: result.recordCount,
          totalProfit: result.totalProfit,
          totalCommission: result.totalCommission,
          totalSwap: result.totalSwap,
          originalTotal: result.originalTotal,
          finalResult: result.finalResult,
          startDate: result.startDate,
          endDate: result.endDate
        })
        console.log('添加结果到表格:', file.name)
      }
    }

    console.log('处理完成，结果数量:', batchResults.value.length)
    if (batchResults.value.length > 0) {
      ElMessage({
        message: `批量处理完成，成功处理 ${batchResults.value.length} 个文件`,
        type: 'success',
        duration: 2000
      })
    } else {
      ElMessage({
        message: '没有成功处理任何文件',
        type: 'warning',
        duration: 2000
      })
    }
  } catch (error) {
    console.error('批量处理错误:', error)
    ElMessage({
      message: '批量处理过程中出错',
      type: 'error',
      duration: 2000
    })
  }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  const date = new Date(dateTimeStr);
  return date.toLocaleString('zh-CN');
}

// 处理单个文件
const processFile = (file) => {
  console.log('开始处理文件:', file.name, '文件对象:', file)

  return new Promise((resolve, reject) => {
    if (!file.raw) {
      console.error(`文件 ${file.name} 没有raw属性`, file)
      ElMessage({
        message: `文件 ${file.name} 格式错误，无法读取`,
        type: 'error',
        duration: 2000
      })
      resolve(null)
      return
    }

    const reader = new FileReader()
    reader.onload = (e) => {
      try {
        console.log(`文件 ${file.name} 读取成功，开始解析`)
        const result = Papa.parse(e.target.result, {
          header: true,
          skipEmptyLines: true
        })



        if (result.data && result.data.length > 0) {
          // 计算总利润、总交易手续费和总库存费
          let totalProfit = 0
          let totalCommission = 0
          let totalSwap = 0

          // 确保数据按照closing_time_utc排序
          const sortedData = [...result.data].filter(row => row.closing_time_utc).sort((a, b) => {
            const dateA = new Date(a.closing_time_utc || 0)
            const dateB = new Date(b.closing_time_utc || 0)
            return dateA - dateB
          })



          // 获取开始和结束时间
          let startDate = null
          let endDate = null

          if (sortedData.length > 0) {
            startDate = sortedData[0].closing_time_utc
            endDate = sortedData[sortedData.length - 1].closing_time_utc


          }

          sortedData.forEach(row => {
            const profit = parseFloat(row.profit_usd || 0)
            const commission = parseFloat(row.commission_usd || 0)
            const swap = parseFloat(row.swap_usd || 0)

            if (!isNaN(profit)) {
              totalProfit += profit
            }

            if (!isNaN(commission)) {
              totalCommission += commission
            }

            if (!isNaN(swap)) {
              totalSwap += swap
            }
          })

          // 计算原始金额：总利润 + 总交易手续费 + 总库存费
          const originalTotal = totalProfit + totalCommission + totalSwap

          // 计算最终结果：原始金额 × 倍数 × 汇率
          const finalResult = originalTotal * multiplier.value * exchangeRate.value

          const resultObj = {
            recordCount: result.data.length,
            totalProfit,
            totalCommission,
            totalSwap,
            originalTotal,
            finalResult,
            startDate,
            endDate
          }


          resolve(resultObj)
        } else {

          ElMessage({
            message: `文件 ${file.name} 没有有效数据`,
            type: 'warning',
            duration: 2000
          })
          resolve(null)
        }
      } catch (error) {
        ElMessage({
          message: `文件 ${file.name} 解析失败`,
          type: 'error',
          duration: 2000
        })
        resolve(null)
      }
    }

    reader.onerror = (error) => {
      ElMessage({
        message: `文件 ${file.name} 读取失败`,
        type: 'error',
        duration: 2000
      })
      resolve(null)
    }

    try {
      reader.readAsText(file.raw)
    } catch (error) {
      console.error(`读取文件 ${file.name} 时出错:`, error)
      ElMessage({
        message: `文件 ${file.name} 读取失败`,
        type: 'error',
        duration: 2000
      })
      resolve(null)
    }
  })
}

// 复制结果到剪贴板
const copyResult = (row) => {
  const content = `用户名：${row.userName}
总利润：${row.totalProfit ? row.totalProfit.toFixed(2) : '0.00'}
手续费：${row.totalCommission ? row.totalCommission.toFixed(2) : '0.00'}
库存费：${row.totalSwap ? row.totalSwap.toFixed(2) : '0.00'}
原始金额：${row.originalTotal ? row.originalTotal.toFixed(2) : '0.00'}
倍数系数：${multiplier.value}
当前汇率：${exchangeRate.value}
结果：${row.finalResult ? row.finalResult.toFixed(2) : '0.00'}`

  // 使用clipboard API复制内容
  try {
    navigator.clipboard.writeText(content).then(() => {
      ElMessage({
        message: '结果已复制到剪贴板',
        type: 'success',
        duration: 1500
      })
    })
  } catch (err) {
    // 如果浏览器不支持clipboard API，使用传统方法
    const textarea = document.createElement('textarea')
    textarea.value = content
    document.body.appendChild(textarea)
    textarea.select()
    document.execCommand('copy')
    document.body.removeChild(textarea)

    ElMessage({
      message: '结果已复制到剪贴板',
      type: 'success',
      duration: 1500
    })
  }
}

// 批量导出到Excel
const exportToExcel = () => {
  if (filteredResults.value.length === 0) {
    ElMessage({
      message: '没有数据可导出',
      type: 'warning',
      duration: 2000
    })
    return
  }

  try {
      // 准备数据
  const exportData = filteredResults.value.map((item, index) => {
    return {
      '序号': index + 1,
      '用户名': item.userName,
      '文件名': item.fileName,
      '开始时间': formatDateTime(item.startDate),
      '结束时间': formatDateTime(item.endDate),
      '记录数': item.recordCount,
      '总利润': item.totalProfit.toFixed(2),
      '手续费': item.totalCommission.toFixed(2),
      '库存费': item.totalSwap.toFixed(2),
      '原始金额': item.originalTotal.toFixed(2),
      '倍数系数': multiplier.value,
      '汇率': exchangeRate.value,
      '结果': item.finalResult.toFixed(2)
    }
  })

    // 创建工作表
    const worksheet = XLSX.utils.json_to_sheet(exportData)

      // 设置列宽
  const columnWidths = [
    { wch: 8 },  // 序号
    { wch: 15 }, // 用户名
    { wch: 20 }, // 文件名
    { wch: 20 }, // 开始时间
    { wch: 20 }, // 结束时间
    { wch: 10 }, // 记录数
    { wch: 12 }, // 总利润
    { wch: 12 }, // 手续费
    { wch: 12 }, // 库存费
    { wch: 12 }, // 原始金额
    { wch: 10 }, // 倍数系数
    { wch: 10 }, // 汇率
    { wch: 12 }  // 结果
  ]
    worksheet['!cols'] = columnWidths

    // 创建工作簿
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, '批量处理结果')

    // 生成Excel文件并下载
    const currentDate = new Date()
    const dateString = `${currentDate.getFullYear()}${String(currentDate.getMonth() + 1).padStart(2, '0')}${String(currentDate.getDate()).padStart(2, '0')}`
    const fileName = `批量处理结果_${dateString}.xlsx`

    XLSX.writeFile(workbook, fileName)

    ElMessage({
      message: `已成功导出到 ${fileName}`,
      type: 'success',
      duration: 2000
    })
  } catch (error) {
    console.error('导出Excel失败:', error)
    ElMessage({
      message: '导出Excel失败',
      type: 'error',
      duration: 2000
    })
  }
}
</script>

<style scoped>
.batch-container {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
  margin: 0;
  overflow: hidden;
}

.batch-wrapper {
  width: 100%;
  max-width: 100%;
  height: 100%;
  background-color: transparent;
  border-radius: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0;
}

.batch-body {
  display: flex;
  padding: 0;
  gap: 24px;
  flex: 1;
  overflow: hidden;
  width: 100%;
  max-width: 100%;
}

.batch-content-wrapper {
  display: flex;
  width: 100%;
  height: 100%;
  gap: 15px;
  max-width: 100%;
  overflow: hidden;
}

.batch-input-section {
  width: 400px;
  /* 固定左侧宽度 */
  min-width: 300px;
  /* 最小宽度 */
  flex-shrink: 0;
  /* 防止收缩 */
  overflow: auto;
}

.batch-result-section {
  flex: 1;
  /* 右侧占用所有剩余空间 */
  min-width: 0;
  /* 确保flex子项可以收缩 */
  overflow: auto;
}

.card {
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
  padding: 24px;
  height: fit-content;
  width: 100%;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.results-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  width: 100%;
}

.empty-results-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.empty-results-content {
  text-align: center;
  color: #a0aec0;
  padding: 60px 0;
}

.empty-results-content i {
  font-size: 64px;
  margin-bottom: 24px;
  opacity: 0.5;
  color: #4a6cf7;
}

.empty-results-content p {
  font-size: 17px;
  font-weight: 500;
  color: #4a5568;
}

.card-title {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  font-size: 18px;
  font-weight: 600;
  color: #2d3748;
  border-bottom: 1px solid #edf2f7;
  padding-bottom: 16px;
  letter-spacing: 0.3px;
}

.card-title i {
  margin-right: 12px;
  font-size: 22px;
  color: #4a6cf7;
}

.card-actions {
  margin-left: auto;
}

.batch-content {
  padding: 16px 0;
}

.batch-params-section {
  margin-top: 24px;
  background-color: white;
  border-radius: 10px;
}

.section-title {
  font-weight: 600;
  font-size: 16px;
  margin-bottom: 20px;
  color: #2d3748;
  border-bottom: 1px solid #edf2f7;
  padding-bottom: 12px;
}

.file-count-info {
  margin-bottom: 20px;
  color: #4a5568;
  font-size: 15px;
  background-color: #f8fafc;
  padding: 12px 16px;
  border-radius: 6px;
  border-left: 3px solid #4a6cf7;
}

.file-count-highlight {
  color: #4a6cf7;
  font-weight: 600;
}

.no-files {
  color: #909399;
  text-align: center;
  padding: 20px 0;
  font-size: 13px;
}

.batch-upload-section {
  margin-bottom: 20px;
}

.upload-area {
  margin-bottom: 16px;
}

.batch-upload-section .el-upload {
  border-radius: 10px;
  border: 2px dashed #e2e8f0;
  background-color: #f8fafc;
  transition: all 0.3s;
}

.batch-upload-section .el-upload:hover {
  border-color: #4a6cf7;
  background-color: #f0f4ff;
}

.batch-upload-section .el-icon-upload {
  font-size: 48px;
  color: #4a6cf7;
  margin-bottom: 16px;
}

.batch-upload-section .el-upload__text {
  color: #4a5568;
  font-size: 16px;
  margin-bottom: 8px;
}

.batch-upload-section .el-upload__text em {
  color: #4a6cf7;
  font-weight: 600;
  font-style: normal;
}

.batch-upload-section .el-upload__tip {
  color: #718096;
  font-size: 14px;
}

.file-list-section {
  margin-top: 16px;
}

.file-list-container {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #edf2f7;
  border-radius: 6px;
  background-color: white;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border-bottom: 1px solid #edf2f7;
}

.file-item:last-child {
  border-bottom: none;
}

.file-item i {
  margin-right: 8px;
  color: #4a6cf7;
  font-size: 16px;
}

.file-name {
  font-size: 14px;
  color: #4a5568;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.delete-btn {
  color: #cbd5e0;
  padding: 2px;
  transition: all 0.2s;
}

.delete-btn:hover {
  color: #e53e3e;
}

.more-files {
  padding: 8px 12px;
  color: #718096;
  font-size: 13px;
  text-align: center;
  background-color: #f7fafc;
  border-top: 1px dashed #e2e8f0;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.copy-btn,
.view-btn {
  font-size: 18px;
  padding: 6px;
  color: #718096;
  transition: all 0.2s;
}

.el-icon {
  font-size: 18px;
}

.copy-btn:hover {
  color: #4a6cf7;
}

.view-btn:hover {
  color: #38b2ac;
}

/* 不再需要batch-settings样式 */

.setting-item {
  margin-bottom: 15px;
}

.setting-label {
  font-weight: 500;
  margin-bottom: 6px;
  color: #606266;
}

.params-row {
  display: flex;
  gap: 15px;
}

.param-item {
  flex: 1;
}

.param-label {
  font-size: 13px;
  margin-bottom: 5px;
  color: #606266;
}

:deep(.el-upload-list) {
  max-height: 150px !important;
  overflow: auto !important;
}

.batch-actions {
  margin-top: 28px;
  display: flex;
  justify-content: center;
}

.batch-actions .el-button {
  padding: 12px 24px;
  font-size: 15px;
  font-weight: 500;
  letter-spacing: 0.3px;
  border-radius: 6px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.batch-results {
  padding: 16px 0;
  overflow: hidden;
  flex: 1;
  display: flex;
  flex-direction: column;
  width: 100%;
}

.highlight-result {
  color: #4a6cf7;
  font-weight: 600;
  font-size: 16px;
}

.highlight-result-without-calculate {
  color: #f7ac4a;
  font-weight: 600;
  font-size: 16px;
}

.highlight-profit {
  color: #2daf0c;
  font-weight: 600;
  font-size: 16px;
}

.batch-summary {
  margin-top: 20px;
  padding: 15px;
  background-color: #f0f9ff;
  border-radius: 6px;
}

.summary-title {
  font-weight: 600;
  font-size: 16px;
  margin-bottom: 10px;
  color: #303133;
}

.summary-content {
  display: flex;
  justify-content: space-between;
}

.summary-item {
  flex: 1;
  text-align: center;
  padding: 10px;
}

.summary-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.summary-value {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.summary-value.highlight {
  color: #409eff;
  font-size: 20px;
}

.batch-filter {
  margin-bottom: 24px;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 20px;
  background-color: #f8fafc;
  border-radius: 10px;
  flex-shrink: 0;
  border: 1px solid #edf2f7;
  align-items: flex-end;
}

.filter-actions {
  display: flex;
  gap: 10px;
  margin-left: auto;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 220px;
}

.filter-label {
  font-size: 14px;
  font-weight: 500;
  color: #4a5568;
  letter-spacing: 0.2px;
}

.date-filter-item {
  min-width: 220px;
}

/* 标记不匹配选择日期的行 */
.mismatch-date {
  color: #f56c6c !important;
  font-weight: bold !important;
  background-color: #fef0f0 !important;
  padding: 2px 5px;
  border-radius: 4px;
}

@media (max-width: 900px) {
  .batch-content-wrapper {
    flex-direction: column;
  }

  .batch-input-section {
    width: 100%;
    max-width: 100%;
    margin-bottom: 20px;
  }

  .batch-result-section {
    width: 100%;
  }
}
</style>